
import cv2
import os,sys
import subprocess
import numpy


# 执行命令
def cmd(cmdStr: str):
    cmds = cmdStr.split(' ')
    proc = subprocess.Popen(
        cmds,
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
    )
    stdout, stderr = proc.communicate()
    # returncode 代表执行cmd命令报错
    if proc.returncode > 0:
        print('cmd erro')
        raise Exception(proc.returncode, stderr)
    return stdout

#方案一
def screencap1():
    cmd('./adbtool/adb.exe shell screencap -p > /sdcard/screen.png')
    cmd('./adbtool/adb.exe pull /sdcard/screen.png ./screen.png')
    return cv2.imread('./screen.png')

def screencap2():
    byteImage = cmd('./adbtool/adb.exe shell screencap -p').replace(b'\r\n', b'\n')
    # opencv读取内存图片
    return cv2.imdecode(numpy.asarray(bytearray(byteImage), dtype=numpy.uint8), cv2.IMREAD_COLOR)

def test():
    winname = 'captest'
    cv2.namedWindow(winname)
    img = screencap2()
    # print(type(img))
    down_points = (int(img.shape[1]/2), int(img.shape[0]/2))
    img = cv2.resize(img, down_points, interpolation= cv2.INTER_LINEAR)
    imgSize = (int(img.shape[1]),int(img.shape[0]))
    cv2.imshow(winname, img)
    key = cv2.waitKey(0)

def test2():
    #adb调用获取截图数据流， ps: 127.0.0.1:7555 为手机的端口号，这里我使用模拟器来测试
    process = subprocess.Popen(
        ['adb', 'shell', 'screencap', '-p'],
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
    )
    stdout = process.stdout.read()
    stdout = stdout.replace(b'\r\n', b'\n')
    #保存图片
    with open('./screnn2.png', 'wb') as f:
        a = f.write(stdout)



if __name__ == '__main__':  
    # test2()
    test()
    
# ————————————————
# 版权声明：本文为CSDN博主「QQQQQYE」的原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。
# 原文链接：https://blog.csdn.net/qinye101/article/details/120000500